import React, { Component } from 'react'
import {Breadcrumb, Card, Divider, Row, Input, Space, Button, Table, Select, Switch, Pagination, Modal, Form, message, Tooltip, Popconfirm } from 'antd'
import { EditOutlined, DeleteOutlined, SettingOutlined } from '@ant-design/icons'

import { getUserList, addUser, changeUserState, editUser, setUser, delUser} from '../../../api/user'
import { getRoles} from '../../../api/right'
import './index.css'
const { Option} = Select;
export default class UsersList extends Component {
  state = {
    userList: [],
    total: 0,
    modalVisibal: false,
    editModalVisibal: false,
    setModalVisibal: false,
    editUserId: null,
    setUserId: null,
    setUserNewId: null,
    parameters: {
      query: '',
      pagenum: 1,
      pagesize: 2
    },
    rolesList: [],
    columns: [
      {
        title: '姓名',
        dataIndex: 'username',
        key: 'username',
        align: 'center'
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        align: 'center',
        key: 'email'
      },
      {
        title: '电话',
        dataIndex: 'mobile',
        align: 'center',
        key: 'mobile'
      },
      {
        title: '角色',
        dataIndex: 'role_name',
        align: 'center',
        key: 'role_name'
      },
      {
        title: '状态',
        dataIndex: 'mg_state',
        align: 'center',
        key: 'mg_state',
        // children:(<Switch />)
        render: (text, record)=>{
          return (<Switch defaultChecked={record.mg_state} 
            onChange={(value) => {
              this.changeState(record.id,value)
            }} />)
        }      
      },
      {
        title: '操作',
        align: 'center',
        render: (text,record) =>{
          return (<Space>
            <Tooltip title='编辑用户信息' placement='top'>
              <Button type='primary' icon={<EditOutlined/>} onClick={ _ => this.showEditUserModal(record)} size='mini'></Button>
            </Tooltip>
            <Tooltip title='删除用户' placement='top'>
            <Popconfirm
              placement="bottomRight"
              title='确定要删除这个用户吗'
              onConfirm={_ => this.deleteUser(record.id)}
              okText="Yes"
              cancelText="No"
            >
      
              <Button type='danger' icon={<DeleteOutlined />} size='mini'></Button>
              </Popconfirm>
            </Tooltip>
            <Tooltip title='分配角色' placement='top'>
              <Button type='default' icon={<SettingOutlined onClick={_ => this.showSetUserModal(record)} />} size='mini'></Button>
            </Tooltip>
          </Space>)
        }
      }
    ]
  }
  changeState = async  (uId,type) =>{
    const res = await changeUserState(uId,type);
    if(res.meta.status === 200){
      message.success(res.meta.msg)
    }else{
      message.error(res.meta.msg)
    }
  }
  getUsers = async (parameters) => {
    const res = await getUserList(parameters);
    if(res.meta.status !== 200){
      message.error(res.meta.msg)
    }else{
      this.setState({
        userList: res.data.users,
        total: res.data.total,
      })
    }
  }
  getRoleList = async () => {
    const res = await getRoles();
    if(res.meta.status !== 200){
      message.error(res.meta.msg)
    }else{
      this.setState({
        rolesList:res.data
      })
    }
  }
  changePagination = async (page,pagesize) => {
    await this.setState({
      parameters:{
        query: this.state.parameters.query,
        pagenum:page,
        pagesize
      }
    })
    this.getUsers(this.state.parameters)
  }
  
  onSearch = async (val) => {
    await this.setState({
      parameters:{
        query: val,
        pagenum: this.state.parameters.pagenum,
        pagesize:this.state.parameters.pagesize
      }
    })
    this.getUsers(this.state.parameters)
  }
  deleteUser = async (id) =>{
    console.log(id)
    const res  = await delUser(id);
    if(res.meta.status === 200){
      message.success(res.meta.msg)
      this.getUsers(this.state.parameters)
    }else{
      message.error(res.meta.msg)
    }
  }
  showAddUserModal = () => {
    this.setState({
      modalVisibal:true,
    })
  }
  showEditUserModal = async (editUser) => {
    await this.setState({
      editModalVisibal:true,
      editUserId: editUser.id,
    })
    this.refs.editUserFormRef.setFieldsValue({
      ['username']: editUser.username,
      ['email']: editUser.email,
      ['mobile']: editUser.mobile
    })
  }
  showSetUserModal = async (setUser) => {
    await this.setState({
      setModalVisibal:true,
      setUserId:setUser.id,
    })
    console.log(this.refs.setUserFormRef)
    this.refs.setUserFormRef.setFieldsValue({
      ['username']: setUser.username,
      ['role_name']: setUser.role_name
    })
  }
  handleOk = ()=>{
    this.refs.addUserFormRef.submit();
  }
  handleOkEdit = () => {
    this.refs.editUserFormRef.submit();
  }
  handleOkSet = () => {
    this.refs.setUserFormRef.submit();
  }
  handleCancel = ()=>{
    this.setState({
      modalVisibal:false,
    })
  }
  handleCancelEdit = () => {
    this.setState({
      editModalVisibal:false,
      editUserId: null,
    })
    this.refs.editUserFormRef.resetFields()
  }
  handleCancelSet = () => {
    this.setState({
      setModalVisibal:false,
      setUserId: null,
      setUserNewId: null,
    })
    this.refs.setUserFormRef.resetFields();
  }
  onFinishAdd = async  (values) => {
    const res  = await addUser(values);
    if(res.meta.status === 201){
      message.success(res.meta.msg)
      this.getUsers(this.state.parameters)
    }else{
      message.error(res.meta.msg)
    }
    this.handleCancel();
  }
  onFinishAddFailed = ({ values, errorFields, outOfDate }) => {
    message.error('请填写完整表单数据再提交！')
  }
  onFinishEditFailed = ({ values, errorFields, outOfDate }) => {
    message.error('请填写完整表单数据再提交！')
  }
  onFinishEdit = async  (values) => {
    // console.log(values)
    const {email, mobile} = values
    // console.log(email,mobile)
    const res  = await editUser(this.state.editUserId,email,mobile);
    console.log(res)
    if(res.meta.status === 200){
      message.success(res.meta.msg)
      this.getUsers(this.state.parameters)
    }else{
      message.error(res.meta.msg)
    }
    this.handleCancelEdit();
  }
  handleSelectChange = (value) =>{
    console.log(value)
    this.setState({
      setUserNewId:value,
    })
  }
  onFinishSet = async  () => {
    const res = await setUser(this.state.setUserId,this.state.setUserNewId)
    if(res.meta.status === 200){
      message.success(res.meta.msg);
      this.getUsers(this.state.parameters);
    }else{
      message.error(res.meta.msg)
    }
    this.handleCancelSet()
  }
  onFinishSetFailed = ({ values, errorFields, outOfDate }) => {
    message.error('请填写完整表单数据再提交！')
  }
  
  componentDidMount(){
    this.getUsers(this.state.parameters)
    this.getRoleList();
  }

  render() {
    return (
      <div>
        <Card className='user-list-card'>
          <Breadcrumb separator=">">
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item href="">用户管理</Breadcrumb.Item>
            <Breadcrumb.Item href="">用户列表</Breadcrumb.Item>
          </Breadcrumb>
          <Divider/>
          <Row>
            <Space direction="vertical">
              <Input.Search placeholder="请输入查询关键字" allowClear onSearch={this.onSearch} style={{width:'100%'}} />
            </Space>
            <Button type='primary' onClick={this.showAddUserModal} style={{marginLeft: '20px'}}>添加用户</Button>
          </Row>
          <Table
            columns={this.state.columns}
            dataSource = {this.state.userList}
            className='user-list-table'
            pagination={false}
            bordered
          />
          <Pagination
            className='user-list-pagination'
            total={this.state.total}
            showSizeChanger
            showQuickJumper
            pageSize={this.state.parameters.pagesize}
            current={this.state.parameters.pagenum}
            pageSizeOptions={[1,2,5,10]}
            showTotal={total => `总共: ${total} 条`}
            onChange={this.changePagination}
          />
        </Card>  
        <Modal title="添加用户" visible={this.state.modalVisibal} onOk={this.handleOk} onCancel={this.handleCancel}>
          <Form
            ref='addUserFormRef'
            name="addUser"
            labelCol={{span:4}}
            labelAlign="right"
            initialValues={{ remember: true }}
            onFinish={this.onFinishAdd}
            onFinishFailed={this.onFinishAddFailed}
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名!' },{min:3,max:8,message:'用户名应在3-8字符'}]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码！' },{min:6,max:16,message:'密码应在6-16字符'}]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[{ required: true, message: '请输入邮箱!' },{pattern:/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,message:'邮箱格式有问题'}]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="手机号"
              name="mobile"
              rules={[{ required: true, message: '请输入手机号！' },{pattern:/^1[0-9]{10}$/,message:'手机号格式不对'}]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="编辑用户" visible={this.state.editModalVisibal} onOk={this.handleOkEdit} onCancel={this.handleCancelEdit}>
        <Form
            ref='editUserFormRef'
            name="editUser"
            labelCol={{span:4}}
            labelAlign="right"
            initialValues={{ remember: true }}
            onFinish={this.onFinishEdit}
            onFinishFailed={this.onFinishEditFailed}
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名!' },{min:3,max:8,message:'用户名应在3-8字符'}]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[{ required: true, message: '请输入邮箱!' },{pattern:/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,message:'邮箱格式有问题'}]}
            >
              <Input  />
            </Form.Item>
            <Form.Item
              label="手机号"
              name="mobile"
              rules={[{ required: true, message: '请输入手机号！' },{pattern:/^1[0-9]{10}$/,message:'手机号格式不对'}]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="分配角色" visible={this.state.setModalVisibal} onOk={this.handleOkSet} onCancel={this.handleCancelSet}>
          <Form
            ref='setUserFormRef'
            name='setUser'
            labelCol={{span:5}}
            labelAlign='right'
            initialValues = {{remember:true}}
            onFinish={this.onFinishSet}
            onFinishFailed={this.onFinishSetFailed}
          >
            <Form.Item
              label="当前用户"
              name="username"
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="当前角色"
              name="role_name"
            >
              <Input  />
            </Form.Item>
            <Form.Item
              label="选择新角色"
              name="newRole"
            >
              <Select  style={{ width: 120 }} onChange={this.handleSelectChange}>
                {this.state.rolesList.map(item=>{
                  return (<Option value={item.id} key={item.id}>{item.roleName}</Option>)
                })}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
